package com.why.config.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.why.entity.Roles;
import com.why.entity.User;
import com.why.mapper.RolesMapper;
import com.why.mapper.TUserMapper;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class DingTalkAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private TUserMapper userMapper;

    @Resource
    private RolesMapper rolesMapper;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("username", (String) authentication.getCredentials());
        User user = userMapper.selectOne(queryWrapper);
        //此处可抛出用户相关异常，如账号禁用等
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (
                Roles roles : rolesMapper.findRoleByUsername(user.getUserName())) {
            authorities.add(new SimpleGrantedAuthority(roles.getCode()));
        }
        return new DingTalkAuthenticationToken(
                new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), authorities),
                authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(DingTalkAuthenticationToken.class);
    }


}
